<template>
  <div class="menu-dialog">
    <el-dialog
      v-model="dialogVisible"
      title="菜单分配"
      width="50%"
      @open="open"
    >
      <div class="dialog-content">
        <el-table
          ref="multipleTableRef"
          :data="tableData"
          style="width: 100%"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="55" />
          <el-table-column prop="key" label="权限字符串" width="180" />
          <el-table-column prop="name" label="描述" />
        </el-table>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submit" :loading="isLoading">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { onMounted, ref } from "vue";
import {
  getPermission,
  linkPermission,
  getRolePermissionList
} from "@/api/system/index";
import { ElMessage, ElTable } from "element-plus";
import { computed } from "vue";
import { PermissionResponse } from "@/api/system/system";
import { reactive } from "vue";
defineOptions({
  name: "menuDialog"
});
interface Props {
  roleId: string;
  modelValue: boolean;
}
const props = defineProps<Props>();
const emits = defineEmits(["update:modelValue", "getList"]);
onMounted(() => {
  getAllPermission();
});
// 获取数据
const query = reactive({
  page: 1,
  pageSize: 100
});
const tableData = ref<PermissionResponse[]>([]);
const total = ref(0);
const getAllPermission = async () => {
  const res = await getPermission(query);
  if (res.code === 0) {
    total.value = res.data.total;
    tableData.value = res.data.pageData;
  }
};

// 获取选择的权限
const multipleTableRef = ref<InstanceType<typeof ElTable>>();

const multipleSelection = ref<PermissionResponse[]>([]);
const handleSelectionChange = (val: PermissionResponse[]) => {
  multipleSelection.value = val;
};

const dialogVisible = computed({
  get() {
    return props.modelValue;
  },
  set(newValue) {
    emits("update:modelValue", newValue);
  }
});
// 获取对应的权限列表
const getRolePermissionLists = async () => {
  const res = await getRolePermissionList(props.roleId);
  if (res.code === 0) {
    res.data.forEach(row => {
      multipleTableRef.value!.toggleRowSelection(row, undefined);
    });
  }
};
const open = () => {
  getRolePermissionLists();
};
// 提交
const isLoading = ref(false);
const submit = async () => {
  const permissionIdList = multipleSelection.value.map(el => el.permissionId);
  const data = {
    roleId: props.roleId,
    permissionIdList
  };
  isLoading.value = true;
  const res = await linkPermission(data);
  if (res.code === 0) {
    ElMessage.success("分配成功");
    isLoading.value = false;
    dialogVisible.value = false;
    emits("getList");
  }
};
</script>
